package com.hzit.hzb.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hzit.common.exception.Assert;
import com.hzit.common.result.ResponseEnum;
import com.hzit.hzb.core.enums.BorrowInfoStatusEnum;
import com.hzit.hzb.core.enums.BorrowerStatusEnum;
import com.hzit.hzb.core.enums.UserBindEnum;
import com.hzit.hzb.core.pojo.entity.BorrowInfo;
import com.hzit.hzb.core.mapper.BorrowInfoMapper;
import com.hzit.hzb.core.pojo.entity.Borrower;
import com.hzit.hzb.core.pojo.entity.Dict;
import com.hzit.hzb.core.pojo.entity.UserInfo;
import com.hzit.hzb.core.pojo.vo.BorrowInfoApprovalVO;
import com.hzit.hzb.core.pojo.vo.BorrowerDetailVO;
import com.hzit.hzb.core.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 借款信息表 服务实现类
 * </p>
 *
 * @author hbxfwf
 * @since 2024-08-27
 */
@Service
public class BorrowInfoServiceImpl extends ServiceImpl<BorrowInfoMapper, BorrowInfo> implements BorrowInfoService {

	@Autowired
	private UserInfoService userInfoService;
	@Autowired
	private BorrowerService borrowerService;
	@Autowired
	private DictService dictService;
	@Autowired
	private LendService lendService;

	/**
	 * 1. 保存借款信息
	 * @param borrowInfo
	 * @param userId
	 */
	@Override
	public void saveBorrowInfo(BorrowInfo borrowInfo, Long userId) {
		// 1.1 得到userInfo信息
		UserInfo userInfo = userInfoService.getById(userId);
		Assert.isTrue(userInfo.getBindStatus().intValue() == UserBindEnum.BIND_OK.getStatus(), ResponseEnum.USER_NO_BIND_ERROR);
		Assert.isTrue(userInfo.getBorrowAuthStatus().intValue() == BorrowerStatusEnum.AUTH_OK.getStatus(),ResponseEnum.USER_NO_AMOUNT_ERROR);


		// 1.2 保存BorrowInfo信息
		borrowInfo.setUserId(userId);
		BigDecimal borrowAmount = borrowerService.getBorrowAmount(userId);
		Assert.isTrue(borrowAmount.doubleValue() >= borrowInfo.getAmount().doubleValue(),ResponseEnum.USER_AMOUNT_LESS_ERROR);
		borrowInfo.setBorrowYearRate(borrowInfo.getBorrowYearRate().divide(new BigDecimal(100))); // 将年利率变为小数
		borrowInfo.setStatus(BorrowInfoStatusEnum.CHECK_RUN.getStatus());                             // 设置审核状态为：审核中。。。

		// 1.3 保存到数据库中
		this.save(borrowInfo);

	}

	/**
	 * 1. 根据用户id查询用户状态值
	 * @param userId
	 * @return
	 */
	@Override
	public Integer getBorrowInfoStatus(Long userId) {
		BorrowInfo borrowInfo = this.getOne(new QueryWrapper<BorrowInfo>().eq("user_id", userId));
		if(borrowInfo == null){
			return BorrowInfoStatusEnum.NO_AUTH.getStatus();
		}
		Integer status = borrowInfo.getStatus();
		return status;
	}

	/**
	 * 根据登录用户id获取借款人信息列表
	 * @return
	 */
	@Override
	public List<BorrowInfo> selectList() {
		// 1.1 查询borrow表与borrow_info表的信息
		List<BorrowInfo> borrowInfoList = baseMapper.selectBorrowInfoList();
		// 1.2 处理上面集合中的字典功能相关的数据 (处理字典相关的数据)
		borrowInfoList.forEach(bi -> {
			Map<String,Object> param = new HashMap<>();
			param.put("returnMethod",borrowerService.getDictNameByDictCodeAndValue("returnMethod",bi.getReturnMethod() + ""));
			param.put("moneyUse",borrowerService.getDictNameByDictCodeAndValue("moneyUse",bi.getMoneyUse() + ""));
			param.put("status",BorrowerStatusEnum.getMsgByStatus(bi.getStatus()));
			bi.setParam(param);
		});
		// 1.3 最后返回
		return borrowInfoList;
	}

	/**
	 * 根据借款id查询借款详细信息及借款人详细信息
	 * @param id
	 * @return
	 */
	@Override
	public Map<String, Object> show(Integer borrowInfoId) {
		// 1.1 获取借款信息
		BorrowInfo bi = this.getById(borrowInfoId);
		bi.getParam().put("returnMethod",borrowerService.getDictNameByDictCodeAndValue("returnMethod",bi.getReturnMethod() + ""));
		bi.getParam().put("moneyUse",borrowerService.getDictNameByDictCodeAndValue("moneyUse",bi.getMoneyUse() + ""));
		bi.getParam().put("status",BorrowerStatusEnum.getMsgByStatus(bi.getStatus()));

		// 1.2 借款人信息
		Long userId = bi.getUserId();
		Borrower borrower = borrowerService.getOne(new QueryWrapper<Borrower>().eq("user_id", userId));
		// 1.3 通过借款人id获取借款详情
		BorrowerDetailVO borrowerDetailVO = borrowerService.getDetailsById(borrower.getId());

		// 1.4 组装数据到map集合中
		Map<String, Object> resultMap = new HashMap<>();
		resultMap.put("borrowInfo",bi);
		resultMap.put("borrower",borrowerDetailVO);

		// 1.5 最后返回
		return resultMap;
	}

	/**
	 * 借款审核
	 * @param vo
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void approval(BorrowInfoApprovalVO vo) {
		// 1. 得到借款id
		Long id = vo.getId();
		// 2. 得到借款信息
		BorrowInfo borrowInfo = this.getById(id);
		// 3. 修改状态
		borrowInfo.setStatus(vo.getStatus());
		// 4. 完成修改
		this.updateById(borrowInfo);

		// 5. 如果审核状态是通过，则产生标的
		if(borrowInfo.getStatus().intValue() == BorrowInfoStatusEnum.CHECK_OK.getStatus()){
			//todo.. 产生标的
			lendService.createLend(vo,borrowInfo);
		}
	}
}

